<template>
  <div>
    <el-page-header @back="$goBack" :content="pageTitle" />
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="背景图" prop="image">
        <xu-upload v-model="form.image" />
      </el-form-item>
      <el-form-item label="名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input type="textarea" v-model="form.description" placeholder="请输入描述信息" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import XuUpload from '../../../components/xu-upload'
import { VipActionsEnum } from '../../../_/vue/store/vip'
export default {
  components: {
    XuUpload
  },
  data () {
    return {
      pageTitle: '添加卡类型',
      loading: false,
      id: '',
      rules: {
        image: [{ required: true, message: '请上传封面', trigger: 'blur' }],
        title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      form: {
        title: '',
        description: ''
      }
    }
  },
  async mounted () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.pageTitle = '编辑卡类型'
      const resp = await this.edit(this.id)
      this.form = resp.data
    }
  },
  methods: {
    ...mapActions({
      store: VipActionsEnum.STORE,
      edit: VipActionsEnum.EDIT,
      save: VipActionsEnum.SAVE
    }),
    submit () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.loading = true
          if (this.id) {
            await this.save({ id: this.id, data: this.form })
          } else {
            await this.store(this.form)
          }
          this.$message.success(this.id ? '保存成功' : '新增成功')
          this.$goBack()
        }
        this.loading = false

        return false
      })
    }
  }
}
</script>
